#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/select.h>
#include "Sock.hpp"
#include "Log.hpp"

using namespace std;
const static int gport = 8080;

class SelectServer{
public:
    SelectServer(uint16_t port = gport):port_(port){

    }

    void InitServer(){
        listenSock_.Socket();
        listenSock_.Bind(port_);
        listenSock_.Listen();
    }

    void HandlerEvent(fd_set &rfds){
        if(FD_ISSET(listenSock_.GetSock(), &rfds)){
            cout << "new connect" << endl;
            //listenSock_.Accept()
        }
    }
    void Start(){
        fd_set rfds;
        FD_ZERO(&rfds);
        FD_SET(listenSock_.GetSock(), &rfds);
        while(true){
            struct timeval timeout = {2,0};//放循环外第二次开始就被覆盖为0了
            //int n = select(listenSock_.GetSock()+1, &rfds, nullptr, nullptr, &timeout);
            int n = select(listenSock_.GetSock()+1, &rfds, nullptr, nullptr, nullptr);
            switch(n){
                case 0:
                    logMessage(Debug, "timeout, %d: %s", errno, strerror(errno));
                    break;
                case -1:
                    logMessage(Warning, "%d: %s", errno, strerror(errno));
                    break;
                default:
                logMessage(Debug, "happen: %d", n);
                break;
            }
        }
    }

    ~SelectServer(){
        listenSock_.Close();
    }

private:
    uint16_t port_;
    Sock listenSock_;
};